<template>
	<view class="store-wrapper" :style="[pageStyle,AppSkinVar]">
		<e-loading-page :loading="loading"  >
			<template #icon>
				<loader ></loader>
			</template>
		</e-loading-page>
		<store-layout :storeId="storeId" :componentsList="componentsList" :onShow="pageShow" @storeInfoUpdate="storeInfoUpdate"
			@share="share" @pageBackgroundImageChange="setPageBackgroundImage"  />
		<!-- <view class="" id="store-sub-container">
			<view class="top-header width-100 e-rela">
				<view class="view-bg e-abso width-100"></view>
				<view class="header-content bg-white e-p-t-15 e-flex-xy-center width-100 e-p-l-20 e-p-r-20 e-abso">
					<view class="e-flex width-100">
						<view class="logo">
							<image :src="$fullLink(storeInfo.logo)" mode="aspectFill" v-if="storeInfo.logo"></image>
							<image :src="$staticPath('store_logo.png')" mode="aspectFill" v-else></image>
						</view>
						<view class="e-m-l-20 e-flex-fill">
							<view class="e-flex e-flex-content-start">
								<text class="store-name fw-500 c-black e-m-r-6">{{ storeInfo.name }}</text>
								<view class="self-icon " v-if="appHasOwn&&storeInfo.hasOwn == 1">
									{{ $t('classify.自营') }}
								</view>
							</view>
							<view class="store-data e-m-t-10 e-font-26 e-flex">
								<text>{{ $t('store.商品') }}</text>
								<text class="e-p-10">{{ storeInfo.productCount }}</text>
								<text class="e-p-r-10 line"></text>
								<text>{{ $t('store.收藏') }}</text>
								<text class="e-p-l-10">{{ storeInfo.collectedCount }}</text>
							</view>
						</view>
						<view class=" e-flex-xy-center">
							<text class="e-font-32 c-primary iconfont icon-fenxiang e-m-r-44" @tap="share"></text>
							<text class="e-font-32 c-primary iconfont icon-shoucang2" v-if="storeInfo.hasCollected == 1" @tap="changeCollage(1)"></text>
							<text class="e-font-32 c-primary iconfont icon-shoucang1" v-else @tap="changeCollage(2)"></text>
						</view>
					</view>
				</view>
			</view>
		</view> -->
		<!-- #ifndef MP-WEIXIN||MP-ALIPAY -->
		<share-popup type="2" :shareUrl="webShareUrl" :mpShareUrl="mpShareUrl" :show="sharePopupShow"
			@close="sharePopupShow = false"></share-popup>
		<!-- #endif -->
		<view class="canvas-box  e-abso ">
			<canvas ref="canvas" class="store-canvas" id="store-canvas" canvas-id="store-canvas"></canvas>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref } from 'vue'
	import {
		useCurrentInstance,
		useLayout,
		useCanvas
	} from '@/common/hooks'
	import { getStoreHomeLayout, getGoodsShareUrl } from '@/common/request/api'
	import type { StoreInfo } from '@/common/request/api'
	import {
		drawQRCode,
		drawRoundedRectangle,
		drawText,
		getTextLineHeight
	} from '@/common/canvas'
	/* 引入uqrcode核心js */
	import { uQRCode,getAppImageInfo } from '@/common/utils'
	// #ifdef MP-WEIXIN
	import { sceneParamsToObj } from '@/common/utils'
	// #endif
	// #ifdef PRIVATE || SUBSCRIPTION
	import { mpShareInit } from '@/common/utils'
	import type { MpShare } from '@/common/utils'
	import { getShareLink } from '@/common/wxInit'
	// #endif
	import { APP_HAS_OWN } from '@/env'
	import { useUser } from '@/common/stores'
	import { storeToRefs } from 'pinia'
	import {
		onShow,
		onHide,
		onReachBottom
	} from '@dcloudio/uni-app'


	const props = defineProps<{
		scene ?: string
		id ?: string
		traceId ?: string
		skuId ?: string
	}>()

	const ctx = useCurrentInstance()
	const {componentsList,pageStyle,isDefaultShare,setPageOption,setPageBackgroundImage} = useLayout(ctx)


	const { isLogin } = storeToRefs(useUser())
	


	const storeId = ref('')
	const storeInfo = ref<StoreInfo>()



	let pageParams : Record<string, any> = {}
	const loading = ref(true)
	const init = () => {
		let query:Record<string, any> = { ...props }
		// #ifdef MP-WEIXIN
		if (props.scene) {
			query = sceneParamsToObj(props.scene)
		}
		// #endif
		pageParams = query

		if (query.id) storeId.value = query.id
		getStoreHomeLayout(storeId.value).then(res => {

			setPageOption(res.data)
		}).finally(() => {
			loading.value = false
		})
	}
	
	init()

	// 更新店铺详情信息，设置页面分享内容
	const storeInfoUpdate = (data:StoreInfo) => {
		storeInfo.value = data
		if(isDefaultShare.value){
			let mpShare = {}
			// #ifdef APP-PLUS
			mpShare = {
				title: data.name,
				path: '', // 默认为当前页面路径
				appParams: pageParams,
				imageUrl: ctx.$fullLink(data.logo),
				appDesc: data.description || ''
			}
			// #endif
			// #ifdef MP-WEIXIN||MP-ALIPAY
			mpShare = {
				title: data.name,
				path: '', // 默认为当前页面路径
				imageUrl: ''
			}
			// #endif
			// #ifdef PRIVATE || SUBSCRIPTION
			mpShare = {
				title: data.name,
				link: getShareLink(),
				imgUrl: ctx.$fullLink(data.logo)
			}
			mpShareInit(mpShare as MpShare)
			// #endif
			uni.$endless.mpShare = mpShare
			
		}
	}
	// isOpen : boolean
	const getImage = (url : string) => {
		// if (url && isOpen) {
		// 	return ctx.$fullLink(url)
		// }
		
		if (url) {
			return ctx.$fullLink(url)
		}
		return ''
	}
	
	const webShareUrl = ref('')
	const { canvasdraw, canvasImgUrl: mpShareUrl } = useCanvas()
	const sharePopupShow = ref(false)
	const draw = async (shareUrl : string) => {
		canvasdraw({
			// 现已调整为hasCustomShare不为1时，接口自动将customShareImg字段设置为店铺第一个商品的第一张图
			// bgImgUrl: getImage(storeInfo.value?.customShareImg, storeInfo.value?.hasCustomShare === 1),
			bgImgUrl: getImage(storeInfo.value?.customShareImg!),
			canvasId: 'store-canvas',
			that: ctx,
			width: 290,
			height: 447,
			bgWidth: 290,
			bgHeight: 290,
			drawIng: async (canvasCtx) => {
				let logoPath = storeInfo.value?.logo
				if(logoPath){

					const logoInfo = await getAppImageInfo(ctx.$fullLink(logoPath))
					let logoWRatio = 1
					let logoHRatio = 1
					if (logoInfo) {
						logoWRatio = logoInfo.width / logoInfo.height
						logoHRatio = logoInfo.height / logoInfo.width
					}
					canvasCtx.drawImage(logoInfo.path, (309 - 74 * logoWRatio) / 2, 253, 74 * logoWRatio, 74 * logoHRatio)
				}
	
				
				let { name = '' } = storeInfo.value!
				let width = canvasCtx.measureText(name).width
				if (width > 72) {
					let chr = name.split('')
					let temp = ''
					for (let a = 0; a < chr.length; a++) {
						if (canvasCtx.measureText(temp).width >= 72) {
							temp = temp.substr(0, temp.length - 2) + '...'
							break
						}
						temp += chr[a]
					}
					name = temp
					width = canvasCtx.measureText(name).width
				}
				drawText(canvasCtx, {
					x: 145 - width,
					y: 348,
					text: name,
					size: 14,
					fillStyle: '#333',
					font: 'normal normal bold 14px'
				})
				
				if (APP_HAS_OWN) {
					drawRoundedRectangle(canvasCtx, {
						x: 150 + (width / 2),
						y: 334,
						width: canvasCtx.measureText(ctx.$t('classify.自营')).width+12,
						height: 16,
						radius: 3,
						lineWidth: 0,
						fillStyle: ctx.AppSkin.primary
					})
					drawText(canvasCtx, {
						x: 154 + (width / 2),
						y: 346,
						text: ctx.$t('classify.自营'),
						size: 11,
						fillStyle: '#fff',
						font: 'normal normal bold 14px'
					})
				}
				drawText(canvasCtx, {
					x: 20,
					y: 388,
					text: '①',
					size: 12,
					fillStyle: '#666',
					font: 'normal normal bold 12px'
				})
				
				const numberW = canvasCtx.measureText('① ').width+4
				canvasCtx.setFontSize(12);
				let {
					row: textList1
				} = getTextLineHeight(canvasCtx, {
					w: 173-numberW,
					text: ctx.$t('store.分享描述1')
				})
				
				textList1.forEach((item,index) => {
					drawText(canvasCtx, {
						x: 20+numberW,
						y: 388+index*14,
						text: item,
						size: 12,
						fillStyle: '#666',
						font: 'normal normal bold 12px'
					})
				})
				
				const textTwoY = 406+(textList1.length-1)*14
				drawText(canvasCtx, {
					x: 20,
					y: textTwoY,
					text: '②',
					size: 12,
					fillStyle: '#666',
					font: 'normal normal bold 12px'
				})
				canvasCtx.setFontSize(12);
				let {
					row: textList2
				} = getTextLineHeight(canvasCtx, {
					w: 173-numberW,
					text: ctx.$t('store.分享描述2')
				})
				textList2.forEach((item,index) => {
					drawText(canvasCtx, {
						x: 20+numberW,
						y: textTwoY+index*14,
						text: item,
						size: 12,
						fillStyle: '#666',
						font: 'normal normal bold 12px'
					})
				})
				const codeY = 360+(((textList1.length+textList2.length-2)*14)/2)
				// #ifdef MP-WEIXIN||MP-ALIPAY
	
				let codePath = await getAppImageInfo(ctx.$fullLink(shareUrl))
				if (codePath.path) {
					canvasCtx.drawImage(codePath.path, 204, codeY, 65, 65)
				}
				// #endif
				// #ifndef MP-WEIXIN||MP-ALIPAY
				drawRoundedRectangle(canvasCtx, {
					x: 204,
					y: codeY,
					width: 65,
					height: 65,
					radius: 0,
					lineWidth: 2,
					strokeStyle: '#E7E7E7'
				})
				drawQRCode(canvasCtx, {
					x: 209,
					y: codeY+5,
					size: 55, //二维码大小
					margin: 0, // 填充边距
					modules: uQRCode.getModules({
						id: 'store-canvas', //canvasId
						mode: 'canvas', // 生成模式
						size: 55, //二维码大小
						margin: 0, // 填充边距
						backgroundColor: '#fff', // 背景色
						foregroundColor: '#000', // 前景色
						errorCorrectLevel: uQRCode.errorCorrectLevel.H, // 纠错等级,
						text: shareUrl
					})
				})
				webShareUrl.value = shareUrl
				// #endif
			}
		}).then(() => {
			
			showShare()
		}).finally(() => {
			uni.hideLoading()
		})


	}
	const share = () => {
		if (isLogin.value) {
			uni.showLoading({
				title: 'loading...'
			})
			getGoodsShareUrl({
				// #ifdef MP-WEIXIN||MP-ALIPAY
				url: 'pages/store/index',
				// #endif
				// #ifndef MP-WEIXIN||MP-ALIPAY
				url: '/pages/store/index',
				// #endif
				// #ifdef  PRIVATE
				formType: 'mp_private',
				// #endif
				// #ifndef  PRIVATE
				formType: getApp().globalData!.payFromType,
				// #endif
				scene: ctx.$getShareUrlScene(`id=${storeId.value}`)
			}).then(res => {
				draw(res.shareUrl)
			})
		} else {
			ctx.$goLogin()
		}
	}
	const showShare = () => {
		// #ifdef MP-WEIXIN
		wx.showShareImageMenu({
			path: mpShareUrl.value
		})
		// #endif
		// #ifndef MP-WEIXIN
		sharePopupShow.value = true
		// #endif
	}

	

	const pageShow = ref(false)
	onShow(() => {
		pageShow.value = true
	})
	onHide(() => {
		pageShow.value = false
	})
	onReachBottom(() => {
		uni.$emit('onStorePageReachBottom')
	})
</script>

<style lang="scss" scoped>
	/*  #ifdef MP-WEIXIN||MP-ALIPAY */
	.share-button {
		margin: 0;
		border-radius: 0;
	}

	/*  #endif */
	.store-wrapper {
		.width-100 {
			width: 100%;
		}

		.lh-16 {
			line-height: 1.6;
		}

		.top-header {
			height: 176rpx;

			.view-bg {
				z-index: 1;
				height: 100rpx;
				background: var(--gradient-primary);
			}

			.header-content {
				z-index: 2;
				bottom: 0;
				height: (176rpx - 30rpx);
				border-radius: 34rpx 34rpx 0 0;

				.logo {
					width: 100rpx;
					height: 100rpx;
					border-radius: 10rpx;
					overflow: hidden;

					image {
						width: 100%;
						height: 100%;
					}
				}

				.store-name {
					@include fontH(30, 42);
				}

				.store-data {
					color: #989898;

					.line {
						width: 1rpx;
						height: 27rpx;
						display: inline-block;
						border-left: 1rpx solid #989898;
					}
				}
			}
		}
	}

	.canvas-box {
		left: -9999px;
		top: -9999px;

		.store-canvas {
			width: 290px;
			height: 447px;
			font-kerning: normal;
		}
	}
</style>